package com.gan.springbootdemo.application;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gan.springbootdemo.util.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Api(description = "图片接收接口")
@Slf4j
@RestController
@RequestMapping("images")
public class ImageController {
    /**
     * request
     */
    @Autowired
    private HttpServletRequest request;

    @ApiOperation("接收图片")
    @PutMapping("/{companyId}")
    public String image(@PathVariable Long companyId) {
        String deviceId = request.getParameter("devID");
        String channelid = request.getParameter("chno");
        String time = request.getParameter("Time");
        String ext = request.getParameter("ext");

        String params = "?devID=" + deviceId + "&chno=" + channelid + "&Time=" + time + "&ext=" + ext;
        String imageUrl = "http://qishon-zuul-gateway.dev.qishon.com/frs/identify/images/1" + params;

        String authorization = "Bearer " + getAccessToken();
        log.info("Authorization: {}", authorization);

        final StringBuilder builder = new StringBuilder();
        HttpURLConnection httpURLConnection;
        try (InputStream is = request.getInputStream()) {
            final URL url = new URL(imageUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置关键值
            httpURLConnection.setRequestMethod("PUT");
            httpURLConnection.setConnectTimeout(20 * 1000);
            httpURLConnection.setReadTimeout(20 * 1000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            // 设置请求头信息
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Authorization", authorization);
            httpURLConnection.connect();

            OutputStream os = httpURLConnection.getOutputStream();
            byte[] buffer = new byte[10240];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
            // 读取响应码
            if (httpURLConnection.getResponseCode() == 200) {
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    builder.append(line);
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        log.info(builder.toString());
        return "OK";
    }

    private String getAccessToken() {
        // 获取文件服务授权码
        String tokenUrl = "http://qishon-zuul-gateway.dev.qishon.com/uaa/oauth-client/token";
        //设置请求参数
        JSONObject params = new JSONObject();
        params.put("client_id", "fileClient");
        params.put("client_secret", "fileClientSecret");
        params.put("companyId", 1);
        String result = HttpUtil.post(tokenUrl, params.toJSONString());
        JSONObject json = JSON.parseObject(result);
        return json.getString("access_token");
    }

}
